package site.addzero.cli.platform

import site.addzero.util.KoinInjector.getSupportStrategty
import java.util.concurrent.TimeUnit

val currentPlatformStrategy = run {
    getSupportStrategty<PlatformStrategy> { it.support } ?: LinuxPlatformStrategy()
}

/**
 * 平台工具类提供跨平台操作
 */
object PlatformTools : PlatformStrategy by currentPlatformStrategy {

    fun isWindows(): Boolean {
        return currentPlatformStrategy.getPlatformType() == PlatformType.WINDOWS
    }


    fun isMac(): Boolean {
        return currentPlatformStrategy.getPlatformType() == PlatformType.MACOS
    }

    fun isUnix(): Boolean {
        return isMac()||isLinux()
    }



    fun isLinux(): Boolean {
        return currentPlatformStrategy.getPlatformType() == PlatformType.LINUX
    }

    /**
     * 交互式执行命令，允许用户与子进程进行交互
     * @param command 要执行的命令
     * @param timeout 超时时间（毫秒）
     * @return CommandResult 命令执行结果
     */
    fun executeCommandInteractive(command: String, timeout: Long = 99999): CommandResult {
        return try {
            val process = when (currentPlatformStrategy.getPlatformType()) {
                PlatformType.WINDOWS -> ProcessBuilder("cmd", "/c", command).inheritIO().start()
                else -> ProcessBuilder("bash", "-c", command).inheritIO().start()
            }

            val finished = process.waitFor(timeout, TimeUnit.MILLISECONDS)

            if (finished) {
                val exitCode = process.exitValue()
                CommandResult(exitCode, "Interactive command completed", "")
            } else {
                process.destroyForcibly()
                CommandResult(-1, "Command timed out", "")
            }
        } catch (e: Exception) {
            CommandResult(-1, "Error executing interactive command: ${e.message}", "Error: ${e.message}")
        }
    }
}


fun String.runCmd(): CommandResult {
    return PlatformTools.executeCommand(this)
}

fun String.runCmdInteractive(): CommandResult {
    return PlatformTools.executeCommandInteractive(this)
}

fun String.runBoolean(): Boolean {
    return runCmd().exitCode == 0
}

fun String.runCode(): Int {
    return runCmd().exitCode
}
